const { Service } = require('egg');
class CollectService extends Service {
  // 新增
  async create(params) {
    try {
      const { ctx } = this;
      const result = await ctx.model.Collect.create(params);
      return result;
    } catch (error) {
      return null;
    }
  }
  // 获取指定类型的所有收藏
  async list({ type, userId }) {
    try {
      const { ctx, app } = this;
      let Op = app.Sequelize.Op;
      // 获取用户指定类型所有id
      const typeArr = await ctx.model.Collect.findAll({
        order: [['created_at', 'DESC']],
        where: { type, userId, flag: 1 },
      });
      // 过滤出条件id
      const typeFilterArr = typeArr.map((v) => v.typeId);
      // 查询对应收藏类型模型
      const typeResultArr = [];
      switch (type) {
        case 1:
          // 查询收藏的房子
          return await ctx.model.User.findAll({
            order: [['created_at', 'DESC']],
            where: {
              userId: {
                [Op.in]: typeFilterArr,
              },
              flag: 1,
            },
          });
          break;
        case 2:
          // 查询收藏的用户
          return await ctx.model.User.findAll({
            where: {
              userId: {
                [Op.in]: typeFilterArr,
              },
              flag: 1,
            },
          });
          break;
        case 3:
          // 查询收藏的资讯
          return await ctx.model.User.findAll({
            order: [['created_at', 'DESC']],
            where: {
              userId: {
                [Op.in]: typeFilterArr,
              },
              flag: 1,
            },
          });
          break;
        default:
          break;
      }
      // console.log(typeResultArr,'typeResultArr');
      
      // return typeResultArr;
    } catch (error) {
      return null;
    }
  }
  //  获取单个收藏
  async info(payload) {
    try {
      const { ctx } = this;
      const result = await ctx.model.Collect.findOne({
        where: {
          ...payload,
          flag: 1,
        },
      });
      return result;
    } catch (error) {
      return null;
    }
  }
  // 修改
  async edit(data) {
    let { collectId } = data;
    try {
      const { ctx } = this;
      const result = await ctx.model.Collect.update(
        { ...data },
        {
          where: {
            collectId,
          },
        }
      );
      return result;
    } catch (error) {
      return null;
    }
  }
  // 删除
  async cancel({collectId,userId}) {
    try {
      const { ctx } = this;
      const result = await ctx.model.Collect.update(
        { flag: 0 },
        {
          where: {
            collectId,
            userId
          },
        }
      );
      return result;
    } catch (error) {
      return null;
    }
  }
}
module.exports = CollectService;
